﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Tubes4_Metnum.Util
{
    public static class Lagrange
    {
        private static StringBuilder expressionBuilder;

        public static double Interpolasi(double[] dataX, double[] dataY, int n, double X)
        {
            double result = 0;
            for (int i = 0; i < n + 1; i++)
            {
                double temp = dataY[i];
                double temp2 = 1;
                for (int j = 0; j < n + 1; j++)
                {
                    if (j != i)
                    {
                        temp2 = temp2 * (X - dataX[j]) / (dataX[i] - dataX[j]);
                    }
                }
                result += temp * temp2;
            }
            return result;
        }

        public static String InterpolasiExp(double[] dataX, double[] dataY, int n)
        {
            expressionBuilder = new StringBuilder();

            // double result = 0;
            for (int i = 0; i < n + 1; i++)
            {
                expressionBuilder.Append("("); 
                expressionBuilder.Append(dataY[i]); // double temp = dataY[i];    
                for (int j = 0; j < n + 1; j++)
                {
                    if (j != i)
                    {
                        // temp2 = temp2 * (X - dataX[j]) / (dataX[i] - dataX[j]);
                        expressionBuilder.Append("*");
                        expressionBuilder.Append("(x-" + dataX[j] + ")/(" + (dataX[i] - dataX[j]) + ")");
                    }
                    else
                    {
                        expressionBuilder.Append("*1");
                    }
                }
                expressionBuilder.Append(")");

                if (i + 1 != n + 1)
                {
                    expressionBuilder.Append("+");
                }
                // result += temp * temp2;
            }
            return expressionBuilder.ToString();
        }

    }
}
